package cn.edu.lingnan.service.impl;

import cn.edu.lingnan.context.BaseContext;
import cn.edu.lingnan.mapper.QuestionStoreMapper;
import cn.edu.lingnan.mapper.QuestionsMapper;
import cn.edu.lingnan.mapper.UserMapper;
import cn.edu.lingnan.service.QuestionsService;
import cn.edu.lingnan.user.dtos.Result;
import cn.edu.lingnan.user.pojos.AIQuestion;
import cn.edu.lingnan.user.pojos.Question;
import cn.edu.lingnan.user.vos.OptionVO;
import cn.edu.lingnan.user.vos.QuestionBankVO;
import cn.edu.lingnan.user.vos.QuestionVO;
import cn.edu.lingnan.user.vos.UserVO;
import cn.hutool.core.bean.BeanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class QuestionsServiceImpl  implements QuestionsService {
    private static final Logger log = LoggerFactory.getLogger(QuestionsServiceImpl.class);
    @Autowired
    private QuestionsMapper questionsMapper;

    @Autowired
    private QuestionStoreMapper questionStoreMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public QuestionBankVO getQuestionStoreTree(Integer storeId) {
        // 获取题库信息
        QuestionBankVO store = questionsMapper.getQuestionStoreById(storeId);
        if (store == null) {
            // 可以选择抛出自定义异常或返回null
            return null;
        }

        // 获取题库下的所有题目
        List<QuestionVO> questions = questionsMapper.getQuestionsByStoreId(storeId);
        if (questions == null || questions.isEmpty()) {
            store.setQuestions(Collections.emptyList());
            return store;
        }

        // 提取所有题目的ID
        List<Integer> questionIds = questions.stream()
                .map(QuestionVO::getQuestionId)
                .collect(Collectors.toList());

        // 获取所有选项
        List<OptionVO> options = questionsMapper.getOptionsByQuestionIds(questionIds);
        // 按 questionId 分组
        Map<Integer, List<OptionVO>> optionsMap = options.stream()
                .collect(Collectors.groupingBy(OptionVO::getQuestionId));

        // 将选项分配给对应的题目
        for (QuestionVO question : questions) {
            question.setOptions(optionsMap.getOrDefault(question.getQuestionId(), Collections.emptyList()));
        }

        // 将题目分配给题库
        store.setQuestions(questions);

        return store;
    }

    @Override
    public QuestionVO getQuestionDetailById(Integer questionId) {
        // 获取题目详情
        QuestionVO questionById = questionsMapper.getQuestionById(questionId);
        if(questionById.getQuestionType()==3 || questionById.getQuestionType()==4){
            return  questionById;
        }
        //选择题查询选项
        List<OptionVO> options = questionsMapper.getOptionsByQuestionId(questionId);
        questionById.setOptions(options);

        return  questionById;
    }

    @Override
    @Transactional
    public void updateQuestionById(QuestionVO questionVO, Integer questionId) {
        // 更新题目
        questionsMapper.updateQuestionById(questionVO, questionId);
        // 更新选项
        List<OptionVO> options = questionVO.getOptions();
        if (options == null || options.isEmpty()) {
            return;
            }
        for (OptionVO option : options) {
            questionsMapper.updateOptionById(option);
        }
    }

    @Override
    @Transactional
    public void addQuestion(QuestionVO questionVO) {
        // 插入题目并获取主键
        questionsMapper.addQuestion(questionVO);
        int questionId = questionVO.getQuestionId(); // 主键值已回填
        log.info("questionId: {}", questionId);

        // 插入选项
        List<OptionVO> options = questionVO.getOptions();
        if (options == null || options.isEmpty()) {
            return;
        }
        for (OptionVO option : options) {
            option.setQuestionId(questionId);
            questionsMapper.addOptions(option);
        }
    }

    @Override
    public Boolean deleteQuestionById(Integer questionId) {
        //题目如果关联试卷，则不能删除
        Integer count = questionsMapper.countQuestionsId(questionId);
        log.info("count: {}", count);
        if(count>0){
            return false;
        }
        int result = questionsMapper.deleteQuestionById(questionId);
        return  result == 1;
    }

    @Override
    public Integer countQuestionsByStoreId(Integer storeId) {
        return  questionsMapper.countQuestionsByStoreId(storeId);
    }

    /**
     * AI驱动插入题目
     *
     * @param aiQuestion
     */
    @Override
    @Transactional
    public Result insertQuestionByAI(AIQuestion aiQuestion) {
        //此功能只允许管理员使用

//        Integer currentId = BaseContext.getCurrentId();
//        //获取用户信息
//     Integer roleId = userMapper.getUserRole(currentId);
//     if(roleId!=null){
//         return Result.success("该功能暂时未向公众开放");
//     }
        //查询图库是否存在,题库名字是AI根据用户数据解析出来的，所以不一定准确或者存在
        if(aiQuestion==null){
            return Result.error("参数错误");
        }
      Integer storeId =  questionStoreMapper.getStoreLikeByName(aiQuestion.getStoreName());
     if(storeId==null){
         return Result.error("题库不存在");
     }
        QuestionVO question = new QuestionVO();
        BeanUtil.copyProperties(aiQuestion,question);
        question.setStoreId(storeId);
        //插入题目，需要返回主键
        questionsMapper.addQuestion(question);

        for (OptionVO option : question.getOptions()) {
            option.setQuestionId(question.getQuestionId());
            questionsMapper.addOptions(option);
        }

        return Result.success(aiQuestion.getQuestionVo());
    }

}
